/*
 * @Author: jiayu
 * @Date: 2022-08-04 16:12:56
 * @LastEditors: jiayu
 * @LastEditTime: 2023-07-31 11:15:15
 * @Description:
 */
import Card from '@/components/Card';
import { Line } from '@ant-design/plots';
import { Button, Popover } from 'antd';
import { Dispatch, memo, SetStateAction, useEffect, useState } from 'react';
import styles from './index.less';

import { FullscreenOutlined, FullscreenExitOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import React from 'react';
import { useModel } from '@umijs/max';
import { instance } from '@/services/jy-api/api';
import { useOrganizationalStore } from '';

const RightContentRender: React.FC<ChartSctionProps> = (props) => {
  const { isModal, full, fullHandle } = props
  const click = () => {
    if (isModal) {
      full && full(false)
    } else {
      fullHandle && fullHandle('section1')
      full && full(true)
    }
  }
  return <div className={styles.rightToolBar}>
    <Button icon={isModal ? <FullscreenExitOutlined /> : <FullscreenOutlined />} onClick={click}></Button>
  </div>
}

export interface ChartSctionProps {
  isModal?: boolean,
  full?: Dispatch<SetStateAction<boolean>>
  fullHandle?: (val: string) => void
}

const Index: React.FC<ChartSctionProps> = memo((props) => {
  const [config, setConfig] = useState<any>()
  const [rankList, setRankList] = useState<any[]>([])
  const { currentDepartmentId } = useModel('organizational')

  const getData = () => {
    instance('/index/Screen/studyDuration', {
      params: {
        department_id: currentDepartmentId
      }
    }).then(data => {
      let x: any[] = []
      const rankData = {}
      data.data.forEach((item: { list: any[]; months: any; }) => {
        const list = item.list.map((_item: any) => {
          if (!rankData[_item.department]) {
            rankData[_item.department] = _item.duration
          } else {
            rankData[_item.department] = rankData[_item.department] + _item.duration
          }
          return {
            ..._item,
            date: item.months,
            category: _item.department.toString()
          }
        })
        x = x.concat(list)
      })
      const _rankList = Object.keys(rankData).map(key => {
        return {
          name: key,
          value: rankData[key]
        }
      }).slice(0, 10)
      setRankList(_rankList.sort((a, b) => b.value - a.value))
      const config = {
        data: x,
        xField: 'date',
        yField: 'duration',
        seriesField: 'category',
        smooth: true,
        yAxis: {
          label: {
            // 数值格式化为千分位
            formatter: (v: any) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
          },
          grid: {
            line: {
              style: {
                stroke: '#8291A9',
                lineWidth: 1,
                lineDash: [4, 5],
                strokeOpacity: 0.7,
              }
            }
          }
        },
        tooltip: {
          title: (val: string) => {
            return `人平均学习时长（分钟）`
          },
          domStyles: {
            'g2-tooltip-title': {
              color: 'red'
            }
          }
        },
        slider: {
          start: 0.7,
          end: 1,
          textStyle: {
            fill: '#ffffff',
            fontSize: '16px',
            fontWeight: 'bold',
          }
        },
        legend: {
          flipPage: false,
          itemName: {
            style: {
              fill: '#ffffff',
              fontSize: 14
            },
          },
          position: 'top-left',
          marker: {
            style: (x: { r: 5, fill: '#5AD8A6', fillOpacity: 1, stroke: null }) => {
              return {
                ...x,
                r: 10,
              }
            },
          }
        }
      }
      setConfig(config)
    })
  }
  useEffect(() => {
    if (currentDepartmentId) {
      getData()
    }
  }, [currentDepartmentId]);

  const Title = () => {
    return <div className={styles.titleContainer}>
      <div className={styles.title}>培训课程平均学习时长</div>
      <Popover content="培训课程平均学习时长描述了该部门的平均每人每月的学习时长(所有人学习总时长÷人数)">
        <ExclamationCircleOutlined className={styles.icon} />
      </Popover>
    </div>
  }

  return (
    <div className={styles.section}>
      <Card TitleRnder={<Title />} RightContentRender={<RightContentRender {...props} />}>
        <div className={styles.container}>
          <div className={styles.left}>
            {config && <Line {...config} />}
          </div>
          <div className={styles.right}>
            <RankList rankList={rankList} />
          </div>
        </div>
      </Card>
    </div>
  );
});

const RankList: React.FC<{ rankList: any[] }> = (props) => {
  const { rankList } = props
  return <div className={styles.rank}>
    <div className={styles.title}>平均学习时长排名</div>
    <div className={styles.list}>
      {
        rankList.map((item, index) => <div className={styles.item}>
          <div className={styles.index}>
            {index + 1}
          </div>
          <div className={styles.name}>
            {item.name}
          </div>
          <div className={styles.num}>
            {(item.value / 60).toFixed(2)}小时
          </div>
        </div>)
      }
    </div>
  </div>
}

export default Index;

